//95_2_62_1  产品 id, cid 活动类型  activityid 活动id    pro_ident 第几个
var icart = {};
//加载本地购买物数据

//#region   主要用出显示本地购物车的数量不用跟服务费进行交互
icart.loadcartlocal=function () {
  return new Promise((resolve) => {
    var app = getApp();
    if(app.globalData.icart){
      resolve( icart.loadcartlocal_data()  ) 
    }
    else
    {
      wx.getStorage({
        key: 'icart',
        success: function (res) {
          // 将数据从缓存里读出
          try {
            app.globalData.icart = JSON.parse(res.data);
           
    
          }
          catch (ex) {
            app.globalData.icart = {};
          }  

          resolve( icart.loadcartlocal_data()  ) 
        },
        fail: function (e) {
          app.globalData.icart = {};   
          resolve( icart.loadcartlocal_data()  ) 
        },
        complete: function (d) {  
       
        }
      })
    }
  }) 
}

icart.loadcartlocal_data =function(){
  var app =getApp();
  var cartdata= app.globalData.icart

  // for(var i in cartdata){

  //   if(cartdata[i].protype==2 && clubid!=cartdata[i].clubid){
    
  //     delete cartdata[i]
  //   }
  // }
  return {cart:cartdata,totalnuminfo:icart.totalnuminfo(cartdata),groupcarnum:icart.groupbyactype(cartdata)}    
} 

icart.groupbyactype=function(htcart){
  var groupht={pro:{},prolimit:{}}

  var temlimitpro=null;
  for(var a in htcart){
   var temattr=  a.split("_");
   switch(temattr[1]){
     case "0":{
       if(!groupht["pro"][temattr[0]]){
        groupht["pro"][temattr[0]]=htcart[a]["num"]
       }
       else
       {
        groupht["pro"][temattr[0]]+=htcart[a]["num"]
       }   
       break;   
     }
     case "1":{
      if(  !groupht["prolimit"][temattr[2]]){
         groupht["prolimit"][temattr[2]]={};
      }
      temlimitpro =groupht["prolimit"][temattr[2]];
      if(!temlimitpro[temattr[0]]){
        temlimitpro[temattr[0]]=htcart[a]["num"]
      }
      else
      {
        temlimitpro[temattr[0]]+=htcart[a]["num"]
      }
      break;   
     }   
   }  
  }


 



  return groupht;
  
},

icart.totalnuminfo=function (icart) {
  var totalnum=0
  var selectednum=0;   
  var sumprice=0
  if(icart)
   {
     for(var a in icart){
      totalnum+= parseInt(icart[a]["num"]) ;
      if(icart[a].ischecked)
      {

        
        selectednum+= parseInt(icart[a]["num"]) ;
        if(a.indexOf("_1_")>0 ){
          sumprice+=icart[a]["num"]*icart[a].activityprice
        }
        else
        {
          sumprice+=icart[a]["num"]*icart[a].realprice
        }
       
      }
     }
   }
  
   return {totalnum,selectednum,sumprice};  
}
//#endregion

icart.loadcart = function () {
  var app = getApp();

  wx.getStorage({
    key: 'icart',
    success: function (res) {
      // 将数据从缓存里读出
      try {
        app.globalData.icart = JSON.parse(res.data);
       

      }
      catch (ex) {
        app.globalData.icart = {};
      }

      // return cart.loadcartPromise();
    },
    fail: function (e) {
      app.globalData.icart = {};

    },
    complete: function (d) {
    }
  })

  
}
icart.loadcartPromise = function () {
 
  var app = getApp();
  if (app.globalData.icart) {

    return icart.loadservedata();
  }
  else {

    return new Promise(function (resolve, reject) {
      wx.getStorage({
        key: 'icart',
        success: function (res) {
          // 将数据从缓存里读出
          try {
         

            app.globalData.icart = JSON.parse(res.data);
            icart.loadservedata().then(function (eda) {
              resolve(eda);
            }, function (edb) {
              reject(edb)
            })
          }
          catch (ex) {
          
            reject({ code: "faill", message: ex });
            app.globalData.icart = {};
          }
        },
        fail: function (e) {
          // reject({ code: "faill", message: e });
          resolve({ code: "success", data: [] });
          app.globalData.icart = {};
        }
      })
    })
  }
}
//订单重复购买
icart.buyagain = function (orderinfo) {
  orderinfo.forEach(function (item) {
    icart.querycartadd(item.keyval, item.num)
  })
}

icart.cleardada=function(){
  var app = getApp()

  return new Promise(function (resolve) {
    if (app.globalData.icart) {

      app.globalData.icart={}
  
      wx.setStorage({
        key: "icart",
        data: JSON.stringify(app.globalData.icart),
        success: function (et) {
          resolve({status:1})
        }    

      })
  
    }

  })
 
},

icart.getnum=function(){

  return new Promise(function (resolve, reject) {
    wx.getStorage({
      key: 'icart',
      success: function (res) {

        if(res.data)
        {

        }
      }      
       
    })
  })
  var app = getApp();
  if(app.globalData.cart){
    
  }

}
icart.loadservedata = function () {
  return new Promise(function (resolve, reject) {
    var app = getApp();
    var postdata = {};
    var keyvalues = Object.keys(app.globalData.icart);
 
    if (keyvalues.length < 1) {
      resolve({ code: "success", data: [] })
    }
    postdata["op"] = "getcartinfo";
    postdata["plugin"] = "integral";
    postdata["keyvalues"] = keyvalues.join(",");
    // if(clubid>0){
    //   postdata['clubid']=clubid
    // }
    app.util.request({
      'url': 'entry/wxapp/integralpro_cart',
      showLoading: false,
      'data': postdata,
      success: function (res) {
        if (res.data.errno == 0 && res.data.data["status"] == 1) {
          var invalidkeys=res.data.data["invalidkeys"];
          if(invalidkeys){
            for(var i in invalidkeys){
              icart.setnum(invalidkeys[i], 0)
            }
          } 
          var data = res.data.data["obj"];
          if (data && data.length > 0) {
            for (var a in data) {
              data[a]["num"] = app.globalData.icart[data[a]["keyval"]]["num"];
              if (app.globalData.icart[data[a]["keyval"]]["ischecked"]) {
                data[a]["ischecked"] = true
              }
              else {
                data[a]["ischecked"] = false;
              }
            }
            resolve({ code: "success", exinfo:res.data.data["exinfo"],data: data, nowtime: res.data.data["nowtime"] })
          }
          else {
            resolve({ code: "warn", data: data, nowtime: res.data.data["nowtime"] })
          }
        }
        else {
          reject({ code: "fail" });
        }
      },
      fail: function (res) {
        reject(((res.data && res.data.message) ? res.data.message : res.errMsg));
      },

    })
  })
}
/**
 * 删除选中
 */
icart.removeselected = function () {
  var app = getApp()
  if (app.globalData.icart) {

    for (var a in app.globalData.icart) {
      if (app.globalData.icart[a].ischecked) {
        delete app.globalData.icart[a]
      }
    }

    wx.setStorage({
      key: "icart",
      data: JSON.stringify(app.globalData.icart),
      success: function (et) {
      }
    })

  }
}
/**
 * 设定选中状态
 * @param {*} keyval 
 * @param {*} chkval 
 */
icart.setchk = function (keyval, chkval) {
  var app = getApp();
  
  app.globalData.icart[keyval]["ischecked"] = chkval;
  wx.setStorage({
    key: "icart",
    data: JSON.stringify(app.globalData.icart),
    success: function (et) {
    }
  })
}
/**
 * 更新数量
 */
icart.setnum = function (keyval, num,ischecked) {
  var app = getApp();
  if (num >= 1 && app.globalData.icart[keyval]) {
    app.globalData.icart[keyval]["num"] = num;

    if(ischecked&& !  app.globalData.icart[keyval]["num"]["ischecked"])
    {
      app.globalData.icart[keyval]["ischecked"]=ischecked;
    }
    
  }
  else {
    delete app.globalData.icart[keyval];

  }
  wx.setStorage({
    key: "icart",
    data: JSON.stringify(app.globalData.icart),
    success: function (et) {
    }
  })

}
//根据keys 快递加入简化步骤，这个有问题暂时不能用
icart.querycartadd = function (keyval, num, ischecked, cid, activityid) {
  var app = getApp();
  if (app.globalData.icart == null) {
    app.globalData.icart = {};
  }
  var attrkeys = keyval.split("_");
  attrkeys[1] = 1
  attrkeys[2] = 0
  if (!cid) {
    cid = 0;
  }

  if (!activityid) {
    activityid = 0;
  }
  if (!ischecked) {
    ischecked = true;
  }
  keyval = attrkeys.join("_");
  if (app.globalData.icart[keyval]) {
    app.globalData.icart[keyval]["num"] = num;
  }
  else {
    app.globalData.icart[keyval] = { keyval, num, activityid, ischecked }
  };
  // cid=0普通订单
  // promodel["keyval"] // "id_cid_activityid_attrs.join"   
  wx.setStorage({
    key: "icart",
    data: JSON.stringify(app.globalData.icart),
    success: function (et) {
    }
  })
},
  /**
   * promodel 加入的产品
   * cid 0普通订单
   * activityid =活动id
   */
  icart.cartadd = function (promodel, cid, activityid) {


    if(!promodel.protype){
      promodel.protype=1
    }
    promodel["ischecked"]=true
    
    var app = getApp();
    if (app.globalData.icart == null) {
      app.globalData.icart = {};
    }
    if (!cid) {
      cid = 0;
    }
    if (!activityid) {
      activityid = 0;
    }
    var arrkeyvals = [];
    arrkeyvals.push(promodel.id);
    arrkeyvals.push(cid);
    arrkeyvals.push(activityid);

    //  //95_2_62_1  产品 id, cid 活动类型  activityid 活动id    pro_ident 第几个 protype产品类型1商城产品2团长产品
    if (promodel.attrs && promodel.attrs.length > 0) {
      var attrs = [];
      for (var a in promodel.attrs) {
        attrs.push(promodel.attrs[a].keyval);
      }
      arrkeyvals.push(attrs.join("x"));
    }
    else {

      arrkeyvals.push("-1");
    }
    arrkeyvals.push(promodel.protype);
    var keyval = arrkeyvals.join("_");

    if (app.globalData.icart[keyval]) {
      app.globalData.icart[keyval]["num"] += parseInt(promodel["num"]);
    }
    else {
      app.globalData.icart[keyval] = promodel;
    }

    if(! app.globalData.icart[keyval]["ischecked"]){
      app.globalData.icart[keyval]["ischecked"] =true
    }
   
    


    // cid=0 普通订单
    // promodel["keyval"] // "id_cid_activityid_attrs.join"   
    wx.setStorage({
      key: "icart",
      data: JSON.stringify(app.globalData.icart),
      success: function (et) {
      }
    })
  }
module.exports = icart